package com.ims.controller.system.login;


import com.ims.controller.base.BaseController;
import com.ims.entity.system.Menu;
import com.ims.entity.system.Role;
import com.ims.entity.system.User;
import com.ims.service.MenuService;
import com.ims.service.RoleService;
import com.ims.service.UserService;
import com.ims.shiro.ShiroSessionService;
import com.ims.util.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 * 总入口
 */
@Controller
public class LoginController extends BaseController {


	@Resource
	private UserService userService;
	@Resource
	private MenuService menuService;
	@Resource
	private RoleService roleService;
    @Resource
    ShiroSessionService session;
	/**
	 * 访问登录页
	 * @return
	 */
	@RequestMapping(value="/login_toLogin")
	public ModelAndView toLogin(HttpServletRequest request, HttpServletResponse response)throws Exception{
		ModelAndView mv = new ModelAndView();

		//PageData pd = new PageData();

		//pd = this.getPageData(request);

		mv.setViewName("system/admin/login");
		//mv.addObject("pd",pd);
		return mv;
	}

	public PageData getPageData(HttpServletRequest request){
		return new PageData(request);
	}



	/**
	 * 请求登录，验证用户
	 */
	@RequestMapping(value="/login_login",produces="application/json;charset=UTF-8")
	@ResponseBody
	public Object login()throws Exception{



		Map<String,String> map = new HashMap<String,String>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String errInfo = "";

		String KEYDATA[] = pd.getString("KEYDATA").replaceAll("IMS", "").replaceAll("IMS", "").split(",TEST,");


		//shiro管理的session
		Subject currentUser = SecurityUtils.getSubject();


		String USERNAME = KEYDATA[0];
		String PASSWORD  = KEYDATA[1];
		pd.put("USERNAME", USERNAME);

		String passwd = new SimpleHash("SHA-1", USERNAME, PASSWORD).toString();	//密码加密
		pd.put("PASSWORD", passwd);
		User user = new User();

		//shiro加入身份验证
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(USERNAME, passwd);

		try {
			subject.login(token);
			if(subject.isAuthenticated()){

				if(Tools.isEmpty(errInfo)){
					errInfo = "success";					//验证成功
				}

			}else{
				token.clear();
				errInfo = "usererror";

			}
		} catch (AuthenticationException e) {
			errInfo = "usererror";
		}

		map.put("result", errInfo);
		return map;
	}

	/**
	 * 访问系统首页
	 */
	@RequestMapping(value="/main/{changeMenu}")
	public ModelAndView login_index(@PathVariable("changeMenu") String changeMenu){
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try{

			//shiro管理的session
			Subject currentUser = SecurityUtils.getSubject();
			//Session session = currentUser.getSession();

			User user = (User)session.getAttribute(Const.SESSION_USER);
			if (user != null) {

				User userr = (User)session.getAttribute(Const.SESSION_USERROL);
				if(null == userr){
					user = userService.getUserAndRoleById(user.getUSER_ID());
					session.setAttribute(Const.SESSION_USERROL, user);
				}else{
					user = userr;
				}
				Role role = user.getRole();
				String roleRights = role!=null ? role.getRIGHTS() : "";
				//避免每次拦截用户操作时查询数据库，以下将用户所属角色权限、用户权限限都存入session
				session.setAttribute(Const.SESSION_ROLE_RIGHTS, roleRights); 		//将角色权限存入session
				session.setAttribute(Const.SESSION_USERNAME, user.getUSERNAME());	//放入用户名

				List<Menu> allmenuList = new ArrayList<Menu>();

				if(null == session.getAttribute(Const.SESSION_allmenuList)){
					allmenuList = menuService.listAllMenu();
					if(Tools.notEmpty(roleRights)){
						for(Menu menu : allmenuList){
							menu.setHasMenu(RightsHelper.testRights(roleRights, menu.getMENU_ID()));
							if(menu.isHasMenu()){
								List<Menu> subMenuList = menu.getSubMenu();
								for(Menu sub : subMenuList){
									sub.setHasMenu(RightsHelper.testRights(roleRights, sub.getMENU_ID()));
								}
							}
						}
					}
					session.setAttribute(Const.SESSION_allmenuList, allmenuList);			//菜单权限放入session中
				}else{
					allmenuList = (List<Menu>)session.getAttribute(Const.SESSION_allmenuList);
				}

				//切换菜单=====
				List<Menu> menuList = new ArrayList<Menu>();

				//切换菜单=====
				menuList = (List<Menu>)session.getAttribute(Const.SESSION_allmenuList);
				if(null == session.getAttribute(Const.SESSION_QX)){
					session.setAttribute(Const.SESSION_QX, this.getUQX(session));	//按钮权限放到session中
				}

				//FusionCharts 报表
				String strXML = "<graph caption='前12个月订单销量柱状图' xAxisName='月份' yAxisName='值' decimalPrecision='0' formatNumberScale='0'><set name='2013-05' value='4' color='AFD8F8'/><set name='2013-04' value='0' color='AFD8F8'/><set name='2013-03' value='0' color='AFD8F8'/><set name='2013-02' value='0' color='AFD8F8'/><set name='2013-01' value='0' color='AFD8F8'/><set name='2012-01' value='0' color='AFD8F8'/><set name='2012-11' value='0' color='AFD8F8'/><set name='2012-10' value='0' color='AFD8F8'/><set name='2012-09' value='0' color='AFD8F8'/><set name='2012-08' value='0' color='AFD8F8'/><set name='2012-07' value='0' color='AFD8F8'/><set name='2012-06' value='0' color='AFD8F8'/></graph>" ;
				mv.addObject("strXML", strXML);
				//FusionCharts 报表

				mv.setViewName("system/admin/index");
				mv.addObject("user", user);
				mv.addObject("menuList", menuList);
			}else {
				mv.setViewName("redirect:/login_toLogin.shtml");//session失效后跳转登录页面
			}


		} catch(Exception e){
			mv.setViewName("redirect:/login_toLogin.shtml");

		}

		mv.addObject("pd",pd);
		return mv;
	}

	/**
	 * 用户注销
	 * @param
	 * @return
	 */
	@RequestMapping(value="/logout")
	public ModelAndView logout() throws Exception {
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();

		//shiro管理的session
		Subject currentUser = SecurityUtils.getSubject();


		session.removeAttribute(Const.SESSION_USER);
		session.removeAttribute(Const.SESSION_ROLE_RIGHTS);
		session.removeAttribute(Const.SESSION_allmenuList);
		session.removeAttribute(Const.SESSION_menuList);
		session.removeAttribute(Const.SESSION_QX);
		session.removeAttribute(Const.SESSION_userpds);
		session.removeAttribute(Const.SESSION_USERNAME);
		session.removeAttribute(Const.SESSION_USERROL);
		session.removeAttribute("changeMenu");

		//shiro销毁登录
		Subject subject = SecurityUtils.getSubject();
		subject.logout();

		pd = this.getPageData();
		String  msg = pd.getString("msg");
		pd.put("msg", msg);

		pd.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); //读取系统名称
		mv.setViewName("system/admin/login");
		mv.addObject("pd",pd);
		return mv;
	}
	/**
	 * 获取用户权限
	 */
	public Map<String, String> getUQX(ShiroSessionService session){
		PageData pd = new PageData();
		Map<String, String> map = new HashMap<String, String>();
		try {
			String USERNAME = session.getAttribute(Const.SESSION_USERNAME).toString();
			pd.put(Const.SESSION_USERNAME, USERNAME);
			String ROLE_ID = userService.findByUId(pd).get("ROLE_ID").toString();

			pd.put("ROLE_ID", ROLE_ID);

			PageData pd2 = new PageData();
			pd2.put(Const.SESSION_USERNAME, USERNAME);
			pd2.put("ROLE_ID", ROLE_ID);

			pd = roleService.findObjectById(pd);



			map.put("adds", pd.getString("ADD_QX"));
			map.put("dels", pd.getString("DEL_QX"));
			map.put("edits", pd.getString("EDIT_QX"));
			map.put("chas", pd.getString("CHA_QX"));

			//System.out.println(map);


		} catch (Exception e) {
			LoggerUtils.logError(e.toString(), e);
		}
		return map;
	}

	/**
	 * 进入tab标签
	 * @return
	 */
	@RequestMapping(value="/tab")
	public String tab(){
		return "system/admin/tab";
	}

	/**
	 * 进入首页后的默认页面
	 * @return
	 */
	@RequestMapping(value="/login_default")
	public String defaultPage(){
		return "system/admin/default";
	}


}
